#include "importdatawidget.h"
#include "ui_importdatawidget.h"
#include "qdebug.h"
#include "QFileDialog"
#include "qdebug.h"
#include "Core/ExcelTool/exceldao.h"
#include "QFile"
#include "QMessageBox"
#include "Core/ADO/goodinfodao.h"
#include "Core/ADO/goodinfo.h"
#include "QVariant"

ImportDataWidget::ImportDataWidget(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ImportDataWidget)
{
    ui->setupUi(this);
    this->setFixedSize(this->width(),this->height());
}

ImportDataWidget::~ImportDataWidget()
{
    delete ui;
}

void ImportDataWidget::on_choose_excel_btn_clicked()
{
    QString file_name = QFileDialog::getOpenFileName(this,tr("选择Excel文件"),"/home",tr("Excel (*.xlsx)"));
    this->ui->file_lab->setText(file_name);
}

void ImportDataWidget::on_import_btn_clicked()
{
    QString file_path = this->ui->file_lab->text();
    QFileInfo file(file_path);
    if(file.exists())
    {
        Datas_List datas_list = ExcelDao::ImportFromExcel(file_path);
        if(datas_list.size() <= 0 )
        {
            qDebug() << QString(" ImportDataWidget::on_import_btn_clicked datas_list.size() %1").arg(QString::number(datas_list.size()));
            return;
        }

        std::vector<GoodInfo> good_info_list;
        for(Datas_List_Item_List list_item_list : datas_list)
        {
            if(list_item_list.size() < 7)
            {
                qDebug() << "data is wrong! ";
                return;
            }
            GoodInfo *info = new GoodInfo();
            info->good_id = list_item_list[0].toString();
            info->good_name = list_item_list[1].toString();
            info->cost_price = list_item_list[2].toString().toDouble();
            info->sale_price = list_item_list[3].toString().toDouble();
            info->inventory = list_item_list[4].toString().toDouble();
            info->img_name = list_item_list[5].toString();
            info->description = list_item_list[6].toString();

            good_info_list.push_back(*info);

            //qDebug() << QString("good_id:  ") << list_item_list[0] << list_item_list[1] << list_item_list[2] << list_item_list[4] ;
        }

        qDebug() << QString(" import excel size:  %1 ").arg(QString::number(good_info_list.size()));
        GoodInfoDao::GetInstance()->Insert(good_info_list);
        this->ui->file_lab->setText("");
        QMessageBox box(QMessageBox::Warning,"导入","导入成功"); //,
        box.setStandardButtons (QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok,QString("确定"));
        box.setFixedSize(400,250);
        box.exec();
    }
    else
    {
        QMessageBox box(QMessageBox::Warning,"错误","选择输入路径有误");
        box.setStandardButtons (QMessageBox::Ok);
        box.setButtonText(QMessageBox::Ok,QString("确定"));
        box.setFixedSize(400,250);
        box.exec();
    }
}

void ImportDataWidget::on_close_btn_clicked()
{
    this->close();
}

